package org.finesys.common.core.handler;

import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;

import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.lang.NonNull;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.ResponseErrorHandler;

/**
 * restClient错误监听
 */
public class RestErrorHandler implements ResponseErrorHandler {

    @Override
    public void handleError(@NonNull URI url, @NonNull HttpMethod method, @NonNull ClientHttpResponse response)
            throws IOException {
        ResponseErrorHandler.super.handleError(url, method, response);
    }

    @Override
    public boolean hasError(@NonNull ClientHttpResponse response) throws IOException {
        return !response.getStatusCode().is2xxSuccessful();
    }

    @Override
    public void handleError(@NonNull ClientHttpResponse response) throws IOException {
        // 响应状态码错误时不抛出异常
        throw new HttpClientErrorException(response.getStatusCode(), response.getStatusText(), response.getHeaders(),
                IOUtils.toByteArray(response.getBody()), StandardCharsets.UTF_8);
    }
}
